package com.upu173.music.activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.andbase.library.app.base.AbBaseActivity;
import com.andbase.library.cache.AbImageCache;
import com.andbase.library.utils.AbLogUtil;
import com.andbase.library.view.sample.AbIndicatorViewPager;
import com.upu173.music.R;
import com.upu173.music.fragment.AlbumViewFragment;
import com.upu173.music.fragment.LrcViewFragment;
import com.upu173.music.global.PlayerData;
import com.upu173.music.model.PlayList;
import com.upu173.music.service.MusicPlayerService;
import com.upu173.music.utils.MusicControler;
import com.upu173.music.utils.MusicUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 播放页面
 */
public class MusicPlayActivity extends AbBaseActivity {

    private AbIndicatorViewPager indicatorViewPager;
    private LrcViewFragment lrcViewFragment;
    private AlbumViewFragment albumViewFragment;
    private List<Fragment> fragmentList = null;
    private Button playButton = null;
    private SeekBar seekBar = null;
    private TextView seekProgress = null;
    private TextView seekTotal = null;
    private AbImageCache cache;
    private boolean isPageStop = false;
    private Handler handlerSeekBar = new Handler();
    private Runnable runnableSeekBar = new Runnable() {
        @Override
        public void run() {

            if(!isPageStop){

                if(indicatorViewPager.getViewPager().getCurrentItem() == 0){
                    albumViewFragment.checkCurrentPlay();
                }else{
                    lrcViewFragment.checkCurrentPlay();
                }

                int currentTime = MusicPlayerService.playerManagerReceiver.getCurrentPosition();
                if(currentTime == 0 || currentTime <=  MusicPlayerService.playerManagerReceiver.getDuration()){
                    seekBar.setProgress(currentTime);
                    seekBar.setMax(MusicPlayerService.playerManagerReceiver.getDuration());

                    seekProgress.setText(MusicUtil.timeToString(currentTime));
                    seekTotal.setText(MusicUtil.timeToString(MusicPlayerService.playerManagerReceiver.getDuration()));
                }

            }

            handlerSeekBar.postDelayed(this,300);

        }
    };

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.music_activity_play);

        Toolbar toolbar = (Toolbar)this.findViewById(R.id.toolbar);

        if(PlayerData.getCurrentPlaySong()!=null){
            initToolbar(toolbar,PlayerData.getCurrentPlaySong().getName(),true);
        }else{
            initToolbar(toolbar,"",false);
        }

        cache = AbImageCache.getInstance(this);

        fragmentList = new ArrayList<Fragment>();
        indicatorViewPager = (AbIndicatorViewPager)this.findViewById(R.id.music_view_pager);

        lrcViewFragment = new LrcViewFragment();
        albumViewFragment = new AlbumViewFragment();

        fragmentList.add(albumViewFragment);
        fragmentList.add(lrcViewFragment);

        indicatorViewPager.setFragmentAdapter(this.getSupportFragmentManager(),fragmentList);
        indicatorViewPager.notifyDataSetChanged();


        initPlayBarView();
	}

    private void initPlayBarView() {
        Button perviousButton = (Button)this.findViewById(R.id.music_bar_pervious);
        playButton = (Button)this.findViewById(R.id.music_bar_play);
        Button nextButton = (Button)this.findViewById(R.id.music_bar_next);

        seekBar = (SeekBar)this.findViewById(R.id.music_seek_bar);
        seekProgress = (TextView)this.findViewById(R.id.music_progress);
        seekTotal = (TextView)this.findViewById(R.id.music_total);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    if(MusicPlayerService.playerManagerReceiver.isPlaying()){
                        MusicControler.seekToReceiver(MusicPlayActivity.this,progress);
                    }

                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        if(MusicPlayerService.playerManagerReceiver!=null && MusicPlayerService.playerManagerReceiver.isPlaying()){
            startPlayUI(PlayerData.getCurrentPlaySong());
        }else{
            pausePlayUI();
        }

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(PlayerData.playList.size() == 0){
                    return;
                }

                if(PlayerData.getCurrentPlaySong() == null){
                    playSong(0);
                }else{
                    if(MusicPlayerService.playerManagerReceiver!=null && !MusicPlayerService.playerManagerReceiver.isPlaying()){
                        startPlay(PlayerData.getCurrentPlaySong());
                    }else{
                        pausePlay();
                    }
                }
            }
        });

        perviousButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                perviousSong();
            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextSong();
            }
        });

    }

    public void perviousSong(){
        if(PlayerData.playList.size() > PlayerData.position - 1 && PlayerData.position - 1 >= 0){
            playSong( PlayerData.position - 1);
        }else{
            playSong(0);
        }
    }

    public void nextSong(){
        if(PlayerData.playList.size() > PlayerData.position + 1){
            playSong( PlayerData.position +1);
        }else{
            playSong(PlayerData.position);
        }
    }

    public void playSong(int position){
        if(PlayerData.getCurrentPlaySong()!=null){
            AbLogUtil.e(pageClassName,"正在播放的歌曲：" + PlayerData.getCurrentPlaySong().getName());
        }else{
            AbLogUtil.e(pageClassName,"正在播放的歌曲：无");
        }
        PlayList playSong = PlayerData.playList.get(position);
        AbLogUtil.e(pageClassName,"开始播放下一首歌曲：" + PlayerData.playList.get(position).getName());
        if(PlayerData.getCurrentPlaySong()!=null && PlayerData.getCurrentPlaySong().getPath().equals(PlayerData.playList.get(position).getPath())){
            AbLogUtil.e(pageClassName,"这是同一首歌曲");
            return;
        }
        playSong(playSong);

    }

    public void playSong(PlayList playSong){
        if(MusicPlayerService.playerManagerReceiver.isPlaying()){
            pausePlayUI();
        }

        startPlay(playSong);

    }

    public void startPlay(PlayList playSong){
        if(PlayerData.getCurrentPlaySong()==null || !playSong.getPath().equals(PlayerData.getCurrentPlaySong().getPath())){
            PlayerData.setCurrentPlaySong(playSong);
            MusicControler.startPlayReceiver(this,playSong.getPath());
        }else{
            MusicControler.startPlayReceiver(this,null);
        }
        startPlayUI(playSong);
    }

    public void pausePlay(){
        MusicControler.pausePlayReceiver(this);
        pausePlayUI();
    }

    public void startPlayUI(PlayList playSong){
        getSupportActionBar().setTitle(playSong.getName());
        handlerSeekBar.postDelayed(runnableSeekBar,500);
        playButton.setBackgroundResource(R.drawable.ic_music_pause);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                albumViewFragment.checkCurrentPlay();
                albumViewFragment.updateUI();
            }
        },200);
    }

    public void pausePlayUI(){
        handlerSeekBar.removeCallbacks(runnableSeekBar);
        playButton.setBackgroundResource(R.drawable.ic_music_play);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                albumViewFragment.checkCurrentPlay();
                albumViewFragment.updateUI();

            }
        },200);

    }


    @Override
    public void onResume() {
        isPageStop = false;
        super.onResume();
    }

    @Override
    public void onStop() {
        isPageStop = true;
        super.onStop();
    }

    @Override
    public void finish() {
	    if(handlerSeekBar!=null){
            handlerSeekBar.removeCallbacks(runnableSeekBar);
        }
        super.finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

